<?php
require_once('functions.php');

function getCEmails()
{
	$conn = getConnection();
	return $conn->query('SELECT * FROM Customer_email');
}

function getCEmail($row)
{ 
		$conn = getConnection();
        $results = $conn->query("SELECT * FROM Customer_email WHERE user_ID='$row[user_ID]' AND email='$row[email]'");
        $row = $results->fetch_assoc();
        $conn->close();
        return $row;
}

function blankEmail($id)
{
	return array('user_ID' => $id, 'email' => null);
} 


function noEmail()
{
	$conn = getConnection();
	$sql = "SELECT u.user_ID, firstName, secondName FROM User u LEFT JOIN Customer_email ce ON u.user_ID = ce.user_ID WHERE ce.user_ID IS NULL";
	$results = $conn->query($sql);
    $conn->close();
       
    return $results;
}

function addEmail($row)
{
        $conn = getConnection();
        $row2 = escapeRow($row, $conn);
        $sql =  "INSERT INTO Customer_email VALUES ('$row2[user_ID]', '$row2[email]')";
        $results = $conn->query($sql);
        $error = $conn->error;
        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}

function deleteEmail($id, $email)
{
		$conn = getConnection();
		$conn->query("DELETE FROM Customer_email WHERE user_ID = '$id' AND email = '$email'");
		$conn->close();
		header('Location: index.php');
}

function saveEmail($row)
{
        $conn = getConnection();
        $row2 = escapeRow($row, $conn);
        
        if (getCEmail($row2))
        	$sql =  "UPDATE Customer_email SET email='$row2[newEmail]' WHERE user_ID='$row2[user_ID]' AND email='$row2[email]'";
        else
        	 $sql =  "INSERT INTO Customer_email VALUES ('$row2[user_ID]', '$row2[newEmail]')";
        	         	 
        $results = $conn->query($sql);
        $error = $conn->error;
        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}

	
